package com.example.basestationforballonproject.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.example.basestationforballonproject.MainActivity;

import android.annotation.SuppressLint;
import android.os.Environment;
import android.util.Log;

@SuppressLint("WorldReadableFiles")
public class ExternalStorageFileWriter {

	private OutputStreamWriter outputStreamWriter;
	private File file;
	private String currentFileName;
	public static final String FILE_NAME = "BaseStation.log";
	private SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss", Locale.GERMAN);


	public ExternalStorageFileWriter() {

		if(!isWritable()) {
			Log.d(MainActivity.LOG_TAG, "no access to file");
			throw new RuntimeException("no access to File");
		}

		this.currentFileName = FILE_NAME;
		file = new File(Environment.getExternalStorageDirectory(), this.currentFileName);

		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				throw new RuntimeException("not created: "+e.getMessage());
			}
		}
	}

	public boolean isWritable() {

		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the media
			return true;

		} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return false;
		} else {
			// Something else is wrong. It may be one of many other states, but all we need
			//  to know is we can neither read nor write
			return false;
		}
	}

	public void fileLog(String stringToLog) {
		try {
			outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file, true));
			outputStreamWriter.append(dateFormat.format(new Date()) + " " + stringToLog + "\n");
			outputStreamWriter.flush();
			outputStreamWriter.close();
		}
		catch (IOException e) {
			Log.e(MainActivity.LOG_TAG, "File write failed: " + e.toString());
		}
	}

	public String getCurrentFileName() {
		return currentFileName;
	}

	public boolean removeFile() {
		if(file.exists())
		{
			return file.delete();
		}
		return true;
	}
}
